mod province;
use province::PROVINCES;
use serde_json::Value;
use std::{collections::HashSet, fs::File, io::Read};

pub fn get_province(city: &str) -> Option<&'static str> {
    for (p, c) in PROVINCES.iter() {
        if *p == city || *c == city {
            return Some(p);
        }
    }
    println!("未找到省份: {}", city);
    None
}

/*
{
    "2": {
        "东莞": ["深圳", "广州", "佛山"],
        "宜昌": ["襄阳", "恩施", "武汉"],
        "台南": ["台中", "高雄", "台北"],
        "深圳": ["广州", "佛山", "东莞", "湛江"],
        "桃园": ["台北", "高雄", "台中"],
        "武汉": ["黄冈", "荆州", "宜昌", "武汉"]
    },
}
*/
pub fn count_provinces() -> String {
    // load "district.json" file
    let mut file = File::open("district.json").expect("文件打开失败");
    let mut data = String::new();
    file.read_to_string(&mut data).expect("文件读取失败");

    // parse the json data
    let parsed: Value = serde_json::from_str(&data).expect("JSON 解析失败");

    let mut result = Vec::<String>::new();

    // 手动处理 JSON 对象
    let mut key = 1;
    while parsed.get(&key.to_string()).is_some() {
        let obj = parsed.get(&key.to_string()).unwrap().as_object().unwrap();
        let mut provinces = HashSet::new();
        for (key, value) in obj {
            let key_province = get_province(key);
            provinces.insert(key_province);
            for city in value.as_array().unwrap() {
                let city_province = get_province(city.as_str().unwrap());
                provinces.insert(city_province);
            }
        }
        println!("{:?}", provinces);
        result.push(provinces.len().to_string());
        key += 1;
    }

    result.join(",")
}
